using FirstTea.Application.DTOs;
using FirstTea.Application.Interfaces;
using FirstTea.Domain.Entities;
using FirstTea.Domain.Repositories;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FirstTea.Application.Services
{
    public class TeaService : ITeaService
    {
        private readonly IRepository<Tea> _teaRepo;
        public TeaService(IRepository<Tea> teaRepo)
        {
            _teaRepo = teaRepo;
        }
        public async Task<TeaDto?> GetByIdAsync(Guid id)
        {
            if (id == Guid.Empty) throw new ArgumentException("茶叶Id不能为空");
            var tea = await _teaRepo.GetByIdAsync(id);
            if (tea == null) return null;
            return new TeaDto { Id = tea.Id, Name = tea.Name, Type = tea.TeaType?.Name, Price = tea.Price, Stock = tea.Stock, Description = tea.Description };
        }
        public async Task<IEnumerable<TeaDto>> GetAllAsync()
        {
            var teas = await _teaRepo.GetAllAsync();
            return teas.Select(t => new TeaDto { Id = t.Id, Name = t.Name, Type = t.TeaType?.Name, Price = t.Price, Stock = t.Stock, Description = t.Description });
        }
        public async Task CreateAsync(TeaDto dto)
        {
            if (dto == null) throw new ArgumentNullException(nameof(dto));
            var tea = new Tea { Name = dto.Name, Price = dto.Price, Stock = dto.Stock, Description = dto.Description };
            await _teaRepo.AddAsync(tea);
            await _teaRepo.SaveChangesAsync();
        }
        public async Task UpdateAsync(TeaDto dto)
        {
            if (dto == null) throw new ArgumentNullException(nameof(dto));
            var tea = await _teaRepo.GetByIdAsync(dto.Id);
            if (tea == null) return;
            tea.Name = dto.Name;
            tea.Price = dto.Price;
            tea.Stock = dto.Stock;
            tea.Description = dto.Description;
            await _teaRepo.UpdateAsync(tea);
            await _teaRepo.SaveChangesAsync();
        }
        public async Task DeleteAsync(Guid id)
        {
            await _teaRepo.DeleteAsync(id);
            await _teaRepo.SaveChangesAsync();
        }
    }
}
